/**
 * 格式化功能测试页面
 */

import React, { useState } from 'react';
import { 
  Card, 
  Input, 
  Select, 
  Button, 
  Space, 
  Typography, 
  Alert,
  Divider,
  Row,
  Col,
  Switch,
  message
} from 'antd';
import { 
  PlayCircleOutlined,
  FileWordOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { aiGenerationService } from '../../services/ai-generation.service';
import DocumentExporter from '../../components/common/DocumentExporter';
import { useModelConfigStore } from '../../stores/model-config.store';

const { TextArea } = Input;
const { Option } = Select;
const { Title, Text, Paragraph } = Typography;

const FormatTest: React.FC = () => {
  // 获取模型配置
  const { configs, loading: configsLoading, fetchConfigs } = useModelConfigStore();
  
  const [userPrompt, setUserPrompt] = useState('请写一篇关于华南理工被撞女生事件的新闻报道，要求客观真实，字数800-1200字。');
  const [writingAngle, setWritingAngle] = useState('news_report');
  const [selectedModelId, setSelectedModelId] = useState<string>('');
  const [enableFormat, setEnableFormat] = useState(true);
  const [generating, setGenerating] = useState(false);
  const [result, setResult] = useState<{
    content: string;
    formatValidation?: {
      isValid: boolean;
      issues: string[];
    };
    conversionInfo?: {
      wasMarkdown: boolean;
      conversionApplied: boolean;
    };
  } | null>(null);

  // 测试数据
  const hotItemId = '68dbb177accacf1f30e9249b';
  const platform = 'weixin';
  
  // 加载模型配置
  React.useEffect(() => {
    fetchConfigs();
  }, [fetchConfigs]);
  
  // 设置默认选中的模型
  React.useEffect(() => {
    if (configs.length > 0 && !selectedModelId) {
      const defaultModel = configs.find(c => c.modelName === 'deepseek-reasoner') || configs[0];
      setSelectedModelId(defaultModel.id);
    }
  }, [configs, selectedModelId]);

  const handleGenerate = async () => {
    if (!userPrompt.trim()) {
      message.warning('请输入创作要求');
      return;
    }
    
    if (!selectedModelId) {
      message.warning('请选择一个AI模型');
      return;
    }
    
    // 获取选中的模型配置
    const selectedConfig = configs.find(c => c.id === selectedModelId);
    if (!selectedConfig) {
      message.error('未找到模型配置');
      return;
    }

    setGenerating(true);
    setResult(null);

    try {
      console.log('=== 开始测试格式化创作 ===');
      console.log('📊 测试参数:');
      console.log('  - 热点ID:', hotItemId);
      console.log('  - 平台:', platform);
      console.log('  - 写作类型:', writingAngle);
      console.log('  - AI模型:', selectedConfig.modelName);
      console.log('  - 模型配置:', selectedConfig);
      console.log('  - 启用格式化:', enableFormat);
      console.log('  - 用户Prompt:', userPrompt);
      console.log('');

      const response = await aiGenerationService.generateHotContentWithFormat(
        hotItemId,
        platform,
        writingAngle,
        userPrompt,
        selectedConfig.modelName,
        enableFormat,
        undefined, // parameters
        {
          provider: selectedConfig.provider,
          apiKey: selectedConfig.apiKey,
          apiBase: selectedConfig.baseUrl
        }
      );

      console.log('=== 生成结果 ===');
      console.log('内容长度:', response.content.length);
      console.log('格式验证:', response.formatValidation);

      if (response.error) {
        message.error(`生成失败: ${response.error}`);
        return;
      }

      setResult({
        content: response.content,
        formatValidation: response.formatValidation,
        conversionInfo: response.conversionInfo
      });

      if (enableFormat && response.formatValidation) {
        if (response.formatValidation.isValid) {
          message.success('内容生成成功，格式符合要求！');
        } else {
          message.warning('内容已生成，但格式可能需要调整');
        }
      } else {
        message.success('内容生成成功');
      }

    } catch (error) {
      console.error('生成失败:', error);
      message.error('生成失败，请检查网络连接和服务状态');
    } finally {
      setGenerating(false);
    }
  };

  return (
    <div style={{ padding: '24px', maxWidth: '1400px', margin: '0 auto' }}>
      <Title level={2}>格式化创作功能测试</Title>
      
      <Alert
        message="测试说明"
        description={
          <div>
            <p>这个页面用于测试AI模型直接按格式要求输出HTML内容的功能。启用格式化后，AI会输出包含样式的HTML，可直接下载为Word文档。</p>
            <p><strong>💡 提示：</strong>打开浏览器控制台可以查看详细的Prompt分类和合并过程！</p>
          </div>
        }
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      <Row gutter={24}>
        {/* 左侧：参数配置 */}
        <Col span={12}>
          <Card title="测试参数配置" size="small">
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
              <div>
                <Text strong>用户创作要求：</Text>
                <TextArea
                  value={userPrompt}
                  onChange={(e) => setUserPrompt(e.target.value)}
                  rows={4}
                  placeholder="请输入具体的创作要求..."
                  style={{ marginTop: 8 }}
                />
              </div>

              <div>
                <Text strong>写作类型：</Text>
                <Select
                  value={writingAngle}
                  onChange={setWritingAngle}
                  style={{ width: '100%', marginTop: 8 }}
                >
                  <Option value="news_report">新闻报道</Option>
                  <Option value="analysis">分析报告</Option>
                  <Option value="commentary">评论文章</Option>
                  <Option value="general">通用格式</Option>
                </Select>
              </div>

              <div>
                <Text strong>AI模型：</Text>
                <Select
                  value={selectedModelId}
                  onChange={setSelectedModelId}
                  style={{ width: '100%', marginTop: 8 }}
                  loading={configsLoading}
                  placeholder="请选择模型配置"
                >
                  {configs.map(config => (
                    <Option key={config.id} value={config.id}>
                      {config.name} ({config.modelName})
                    </Option>
                  ))}
                </Select>
              </div>

              <div>
                <Space>
                  <Text strong>启用格式化：</Text>
                  <Switch
                    checked={enableFormat}
                    onChange={setEnableFormat}
                    checkedChildren="开"
                    unCheckedChildren="关"
                  />
                </Space>
              </div>

              <Button
                type="primary"
                size="large"
                icon={<PlayCircleOutlined />}
                loading={generating}
                onClick={handleGenerate}
                block
              >
                {generating ? '正在生成...' : '开始测试'}
              </Button>
            </Space>
          </Card>

          {/* 测试环境信息 */}
          <Card title="测试环境" size="small" style={{ marginTop: 16 }}>
            <div style={{ fontSize: '12px', color: '#666' }}>
              <p><strong>热点ID：</strong>{hotItemId}</p>
              <p><strong>平台：</strong>{platform}</p>
              <p><strong>API地址：</strong>http://localhost:8002</p>
              <p><strong>测试话题：</strong>华南理工的被撞女生，集齐了所有悲伤点</p>
            </div>
          </Card>
        </Col>

        {/* 右侧：结果展示 */}
        <Col span={12}>
          <Card 
            title="生成结果" 
            size="small"
            extra={
              result?.content && (
                <Space>
                  <DocumentExporter
                    content={result.content}
                    title={`测试_${writingAngle}_${new Date().toISOString().split('T')[0]}`}
                  />
                </Space>
              )
            }
          >
            {!result && (
              <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
                <EyeOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                <p>点击"开始测试"查看生成结果</p>
              </div>
            )}

            {result && (
              <>
                {/* 转换信息 */}
                {enableFormat && result.conversionInfo && (
                  <Alert
                    message="格式转换信息"
                    description={
                      <div>
                        <p><strong>原始格式：</strong>{result.conversionInfo.wasMarkdown ? 'Markdown' : 'HTML'}</p>
                        <p><strong>格式转换：</strong>{result.conversionInfo.conversionApplied ? '✅ 已应用' : '❌ 未应用'}</p>
                        {result.conversionInfo.wasMarkdown && (
                          <p style={{ color: '#1890ff' }}>
                            💡 AI输出了Markdown格式，系统已自动转换为HTML格式
                          </p>
                        )}
                      </div>
                    }
                    type="info"
                    style={{ marginBottom: 16 }}
                  />
                )}

                {/* 格式验证结果 */}
                {enableFormat && result.formatValidation && (
                  <Alert
                    message={
                      <Space>
                        <span>格式验证：{result.formatValidation.isValid ? '✅ 通过' : '⚠️ 需要注意'}</span>
                      </Space>
                    }
                    description={
                      !result.formatValidation.isValid && result.formatValidation.issues.length > 0 ? (
                        <ul style={{ margin: 0, paddingLeft: 20 }}>
                          {result.formatValidation.issues.map((issue, index) => (
                            <li key={index}>{issue}</li>
                          ))}
                        </ul>
                      ) : '格式完全符合要求'
                    }
                    type={result.formatValidation.isValid ? 'success' : 'warning'}
                    style={{ marginBottom: 16 }}
                  />
                )}

                {/* 内容预览 */}
                <div 
                  style={{ 
                    maxHeight: '500px', 
                    overflow: 'auto',
                    border: '1px solid #d9d9d9',
                    borderRadius: '6px',
                    background: '#fff'
                  }}
                >
                  {enableFormat ? (
                    <div 
                      style={{ padding: '20px' }}
                      dangerouslySetInnerHTML={{ __html: result.content }}
                    />
                  ) : (
                    <pre style={{ 
                      padding: '20px', 
                      margin: 0, 
                      whiteSpace: 'pre-wrap',
                      fontFamily: 'inherit',
                      fontSize: '14px'
                    }}>
                      {result.content}
                    </pre>
                  )}
                </div>

                {/* 原始HTML代码 */}
                {enableFormat && (
                  <>
                    <Divider />
                    <details>
                      <summary style={{ cursor: 'pointer', fontWeight: 'bold' }}>
                        查看原始HTML代码
                      </summary>
                      <pre style={{ 
                        background: '#f5f5f5', 
                        padding: '12px', 
                        borderRadius: '4px',
                        fontSize: '12px',
                        maxHeight: '200px',
                        overflow: 'auto',
                        marginTop: '8px'
                      }}>
                        {result.content}
                      </pre>
                    </details>
                  </>
                )}
              </>
            )}
          </Card>
        </Col>
      </Row>

      {/* 格式说明 */}
      <Divider />
      <Card title="格式标准说明" size="small">
        <Row gutter={16}>
          <Col span={8}>
            <Title level={5}>一级标题</Title>
            <ul>
              <li>字体：黑体</li>
              <li>字号：三号(16pt)</li>
              <li>对齐：左对齐</li>
              <li>间距：段前段后空1行</li>
            </ul>
          </Col>
          
          <Col span={8}>
            <Title level={5}>二级标题</Title>
            <ul>
              <li>字体：黑体</li>
              <li>字号：四号(14pt)</li>
              <li>对齐：左对齐</li>
              <li>间距：段前段后空0.5行</li>
            </ul>
          </Col>
          
          <Col span={8}>
            <Title level={5}>正文</Title>
            <ul>
              <li>字体：仿宋GB-2312</li>
              <li>字号：小四号(12pt)</li>
              <li>对齐：两端对齐</li>
              <li>缩进：首行缩进两个字符</li>
            </ul>
          </Col>
        </Row>
      </Card>

      {/* Prompt结构说明 */}
      <Divider />
      <Card title="📋 Prompt结构说明" size="small">
        <Row gutter={16}>
          <Col span={12}>
            <Title level={5}>5层Prompt结构</Title>
            <div style={{ background: '#f6f8fa', padding: '12px', borderRadius: '6px' }}>
              <p><strong>📝 [1] Template Prompt</strong> - 角色定义、风格控制</p>
              <p><strong>🔧 [2] System Prompt</strong> - 规范约束、上下文信息</p>
              <p><strong>🤖 [3] Smart Prompt</strong> - 任务指导、智能建议</p>
              <p><strong>🖥️ [4] Frontend Prompt</strong> - 界面层格式要求</p>
              <p><strong>👤 [5] User Input</strong> - 用户个性化要求</p>
            </div>
          </Col>
          
          <Col span={12}>
            <Title level={5}>合并策略</Title>
            <div style={{ background: '#f0f2f5', padding: '12px', borderRadius: '6px' }}>
              <p><strong>顺序叠加：</strong>按优先级依次合并</p>
              <p><strong>优先级递增：</strong>后面的层级优先级更高</p>
              <p><strong>智能转换：</strong>自动检测和转换格式</p>
              <p><strong>质量验证：</strong>多维度评估Prompt质量</p>
            </div>
          </Col>
        </Row>
        
        <Divider />
        
        <Alert
          message="🔍 调试提示"
          description="打开浏览器控制台(F12)可以查看详细的Prompt分析，包括各层内容、结构图表、质量评估等信息。"
          type="success"
          showIcon
        />
      </Card>
    </div>
  );
};

export default FormatTest;
